#include "znx_proc.h"
#include "znx_tcp_proc.h"
#include "znx_worker_proc.h"
#include "znx_openssl.h"
#include "comm/znx_module.h"
#include "conf/znx_core_conf.h"
#include "conf/znx_http_site_mgr.h"

volatile znx_bool_t proc_exit = ZNX_FALSE;
znx_atomic_int64_t  server_conns = 0;
znx_atomic_int64_t  client_conns = 0;


void
znx_proc_init()
{
    znx_ssl_init();
    znx_g_listeners_init();
    znx_worker_processor_init();

    znx_modules_init();
    znx_http_site_mgr_init();

    znx_worker_processor_add_init_hook(znx_modules_worker_init_handle);
    znx_worker_processor_add_proc_exit_hook(znx_modules_worker_proc_exit_handle);
    znx_worker_processor_add_quit_hook(znx_modules_worker_exit_handle);
}


void
znx_proc_shut_down()
{
    proc_exit = ZNX_TRUE;

    znx_g_listeners_close();

    znx_tcp_accepter_stop();

    znx_worker_process_quit();
    while (znx_atomic_int64_load(&server_conns) != 0) {
        usleep(10000);
    }
    while (znx_atomic_int64_load(&client_conns) != 0) {
        usleep(10000);
    }
    while (!znx_worker_processor_all_task_done()) {
        usleep(10000);
    }
    znx_worker_processor_stop();

    znx_modules_main_exit_exec();

    znx_ssl_session_cache_destroy();
    znx_http_site_mgr_destroy();
    znx_http_main_destroy();
    znx_core_conf_destroy();
    znx_mem_clean();
    znx_4kaligned_mem_clean();
}